import { defineStore } from "pinia";
import {
  type TokenResult,  
  getTokenApi
} from "@/api/token";
import {
  tokenType,
  storageLocal,
  store
} from "../utils";
import { type TokenInfo, setToken, TokenKey } from "@/utils/authForToken";

export const useTokenStore = defineStore({
  id: "current_token",
  state: (): tokenType => ({
    // token
    accessToken: storageLocal().getItem<TokenInfo<number>>(TokenKey)?.accessToken ?? "",
    // 时间戳
    expires: storageLocal().getItem<TokenInfo<number>>(TokenKey)?.expires ?? -1
  }),
  actions: {    
    /** 刷新`token` */
    async handGetToken(data) {
      return new Promise<TokenResult>((resolve, reject) => {
        
        getTokenApi(data)
          .then(data => {
            if (data) {
              setToken(data.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useTokenStoreHook() {
  return useTokenStore(store);
}
